package com.rickpan.config;

import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

/**
 * Socket.IO服务器配置
 */
@org.springframework.context.annotation.Configuration
@ComponentScan("com.rickpan.socketio")
public class SocketIOConfig {

    @Value("${socketio.host:localhost}")
    private String host;

    @Value("${socketio.port:9092}")
    private Integer port;

    @Value("${socketio.bossCount:1}")
    private int bossCount;

    @Value("${socketio.workCount:100}")
    private int workCount;

    @Value("${socketio.allowCustomRequests:true}")
    private boolean allowCustomRequests;

    @Value("${socketio.upgradeTimeout:1000000}")
    private int upgradeTimeout;

    @Value("${socketio.pingTimeout:6000000}")
    private int pingTimeout;

    @Value("${socketio.pingInterval:25000}")
    private int pingInterval;

    /**
     * Socket.IO服务器配置
     */
    @Bean
    public SocketIOServer socketIOServer() {
        Configuration config = new Configuration();

        // 基本配置
        config.setHostname(host);
        config.setPort(port);

        // 线程配置
        config.setBossThreads(bossCount);
        config.setWorkerThreads(workCount);

        // 连接配置
        config.setAllowCustomRequests(allowCustomRequests);
        config.setUpgradeTimeout(upgradeTimeout);
        config.setPingTimeout(pingTimeout);
        config.setPingInterval(pingInterval);

        // CORS配置
        config.setOrigin("*");

        // Jackson配置 - 支持Java 8时间类型
        config.setJsonSupport(new com.corundumstudio.socketio.protocol.JacksonJsonSupport(new JavaTimeModule()));

        // 认证配置
        config.setAuthorizationListener(data -> {
            // 这里可以添加JWT token验证逻辑
            String token = data.getSingleUrlParam("token");
            if (token != null && !token.isEmpty()) {
                // TODO: 验证JWT token
                return true;
            }
            // 开发阶段允许所有连接
            return true;
        });

        return new SocketIOServer(config);
    }

    /**
     * Spring注解扫描器，用于扫描Socket.IO事件处理器
     */
    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
        return new SpringAnnotationScanner(socketServer);
    }
}
